package reverseNodesInKGroup;

public class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        int size = 0;
        ListNode cur = head;
        while (cur != null) {
            cur = cur.next;
            size++;
        }
        int left = 1, right = k;
        ListNode dummy = new ListNode(0, head);
        ListNode p0 = dummy;
        ListNode pre = null;
        cur = head;
        ListNode ext;
        while (right <= size) {
            for (int i = 0; i < (right - left + 1); i++) {
                ext = cur.next;
                cur.next = pre;
                pre = cur;
                cur = ext;
            }
            p0.next.next = cur;
            ext = p0.next;
            p0.next = pre;
            p0 = ext;
            pre = null;
            left = right + 1;
            right += k;
        }
        return dummy.next;
    }
}
